<?php

function change_query( $addto_query, $queryOld = NULL )
{
    // change the QUERY_STRING adding or changing the value passed
    if ( $queryOld === NULL )
    {
        $query1 = $_SERVER[ 'QUERY_STRING' ];
    }
    else
    {
        $query1 = $queryOld;
    }
    parse_str( $query1, $array1 );
    parse_str( $addto_query, $array2 );

    $array3 = array();
    foreach ( $array1 as $key => $item )
    {
        $key = str_replace( 'amp;', '', $key );
        $array3[ $key ] = $item;
    }
    $newQuery = array_merge( $array3, $array2 );

    foreach ( $newQuery as $key => $item )
    {
        $newQry[] = $key . '=' . $item;
    }
    return implode( '&', $newQry );
}

// CLEAN ILLEGAL CHARACTERS
function clean_filename( $source_file )
{
    $search[] = " ";
    $search[] = "&";
    $search[] = "$";
    $search[] = ",";
    $search[] = "!";
    $search[] = "@";
    $search[] = "#";
    $search[] = "^";
    $search[] = "(";
    $search[] = ")";
    $search[] = "+";
    $search[] = "=";
    $search[] = "[";
    $search[] = "]";
    $replace[] = "_";
    $replace[] = "and";
    $replace[] = "S";
    $replace[] = "_";
    $replace[] = "";
    $replace[] = "";
    $replace[] = "";
    $replace[] = "";
    $replace[] = "";
    $replace[] = "";
    $replace[] = "";
    $replace[] = "";
    $replace[] = "";
    $replace[] = "";
    return str_replace( $search, $replace, $source_file );
}

function write_ini_file( $file, array $options )
{
    $tmp = '';
    foreach ( $options as $section => $values )
    {
        $tmp .= "[$section]\n";
        if ( is_array( $values ) )
        {
            foreach ( $values as $key => $val )
            {
                if ( is_array( $val ) )
                {
                    foreach ( $val as $k => $v )
                    {
                        $tmp .= "{$key}[$k] = \"$v\"\n";
                    }
                }
                else
                    $tmp .= "$key = \"$val\"\n";
            }
        }
        $tmp .= "\n";
    }
    file_put_contents( $file, $tmp );
    unset( $tmp );
}
